package com.kfm.controller;

import com.kfm.entity.User;
import com.kfm.ex.ServiceException;
import com.kfm.service.UserService;
import com.kfm.util.Contains;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping({"/login","/"})
    public ModelAndView toLogin(){
       return new ModelAndView("login");
    }
    @PostMapping("/login")
    public ModelAndView login(ModelAndView mv,String captcha ,@Validated User user, Errors errors, HttpSession session,
                              HttpServletRequest request){
            if (errors.hasErrors()){
                throw new ServiceException("用户或密码不能为空");
            }
            if (!CaptchaUtil.ver(captcha,request)){
                CaptchaUtil.clear(request);
                mv.addObject("msg","验证码错误");
                mv.setViewName("login");
            }else{
                User login = userService.login(user);
                if (login != null){
                    //登录
                    session.setAttribute(Contains.LOGIN_USER,login);
                    mv.setViewName("redirect:index");
                }else {
                    mv.addObject("msg","用户名或密码不正确");
                    mv.setViewName("login");
                }
            }
        return mv;
    }

    @GetMapping("/index")
    public ModelAndView index(){
        return new ModelAndView("index");
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CaptchaUtil.out(request, response);
    }

    @GetMapping("/info")
    public ModelAndView showInfo(ModelAndView mv){
        mv.setViewName("info");
        return mv;
    }
    @GetMapping("/user")
    public ModelAndView user(ModelAndView mv,User user,HttpSession session){

        List<User> users = userService.fandAll(user);
        session.setAttribute(Contains.USERS,users);
        mv.setViewName("user");
        return mv;
    }

    @GetMapping("/delete")
    public ModelAndView delect(ModelAndView mv ,String id){
        userService.delete(id);
        mv.setViewName("login");
        return mv;
    }
    @GetMapping("/welcome")
    public ModelAndView toWelcome(){
        return new ModelAndView("welcome");
    }
}
